package com.alstudio.ui.module.image.browser;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALPhoto;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.utils.android.AndroidMultiMediaManager;
import com.alstudio.utils.android.device.ALDisplayMetricsManager;
import com.alstudio.utils.android.imageProcess.ALImageProcessParams;
import com.alstudio.utils.android.net.http.UploadPhotoRequest;
import com.alstudio.utils.log.ALLog;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.alstudio.view.listener.AlDialogOnClickListener;
import com.alstudio.view.listener.AlItemOnClickListener;
import com.alstudio.view.toast.MyToastUtil;
import com.loovee.imaohu.R;

/**
 * @author Dengyh
 * @version 2014-03-29 类描述 查看相册大图
 */
public class LargerPhotoActivity extends TitleBarActivity {

	private int index;
	private ArrayList<ALPhoto> photos;

	private ViewPager photo_pager;
	// 显示大图
	private ImagePagerAdapter adapter;

	// 显示的是否是我的个人头像
	private boolean isMyIcon = true;

	private final int TAKE_FOR_REPLACE = 0;
	private final int SELECT_FOR_REPLACE = 1;
	private final int DELETE_PIC = 2;
	private final int SET_MAJOR_PIC = 3;

	private boolean isChange = false;
	private boolean isDel = false;

	private ALImageProcessParams mPhotoProcessParam = new ALImageProcessParams();

	// v认证文字说明
	private TextView warting_text_view;
	// v认证图片
	private ImageView icon_mark_view;
	// v认证布局
	private View alert_view;

	private int vPos = -1;

	private boolean isForTom = false;

	private boolean isHideTitleBar;
	private Handler mHandler = new Handler() {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.Handler#handleMessage(android.os.Message)
		 */
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (isHideTitleBar) {
				showTitleBar();
				isHideTitleBar = false;
			} else {
				invisiableTitleBar();
				isHideTitleBar = true;
			}
		}

	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setupView(this, getClass().getSimpleName());
		initData();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#setupView(android.content.Context,
	 * java.lang.String)
	 */
	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setTitleBarActivityContentView(R.layout.larger_photo_layout);
		initUI();
	}

	private void initUI() {
		photo_pager = (ViewPager) findViewById(R.id.photo_pager);

		photo_pager.setPageMargin((int)ALDisplayMetricsManager
				.getScreenDensity(getApplicationContext()) * 20);

		// 预加载一个
		photo_pager.setOffscreenPageLimit(1);

		alert_view = findViewById(R.id.alert_view);

		warting_text_view = (TextView) findViewById(R.id.warting_text_view);
		icon_mark_view = (ImageView) findViewById(R.id.icon_mark_view);

		photo_pager.setOnPageChangeListener(mOnPageChangeListener);
		setPhotoParam();
	}

	private void setPhotoParam() {
		mPhotoProcessParam.setRequestHeight(640);
		mPhotoProcessParam.setRequestWidth(640);
		mPhotoProcessParam.setExplicitCrop(true);
		mPhotoProcessParam
				.setSavePath(AndroidMultiMediaManager.TEMP_TAKE_PHOTO_FILE_PATH);
	}

	private OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			index = arg0;
			ALLog.e("当前的位置是：" + index);
			setCenterTextViewMessage((index + 1) + "/" + photos.size());
			changeAlertView(arg0);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}
	};

	private void changeAlertView(int pos) {
		if (pos == vPos) {
			if (isForTom) {
				icon_mark_view.setBackgroundResource(R.drawable.photo_tip2);
				warting_text_view.setText(R.string.TxtViewLargePicNotAuthed);
			} else {
				icon_mark_view.setBackgroundResource(R.drawable.photo_tip1);
				warting_text_view.setText(R.string.TxtViewLargePicAuthed);
			}
			// findViewById(R.id.alert_view).setVisibility(View.VISIBLE);
			showAletView();

		} else {
			// findViewById(R.id.alert_view).setVisibility(View.GONE);
			hideAlertView();
		}
	}

	private void showAletView() {
		findViewById(R.id.alert_view).setVisibility(View.VISIBLE);

	}

	private void hideAlertView() {
		findViewById(R.id.alert_view).setVisibility(View.GONE);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		index = getIntent().getIntExtra("index", 0);
		isMyIcon = getIntent().getBooleanExtra("isMyIcon", false);
		initPhotoScrollViewPager();
		photo_pager.setCurrentItem(index);

		vPos = getIntent().getIntExtra("vPos", -1);
		if (isMyIcon) {
			setRightButtonName(R.string.BtnEdit);
			setRightButtonClickListener(this);
			if (ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 2) {
				isForTom = true;
			}
		}
		changeAlertView(index);
	}

	/**
	 * 初始化图片滚动显示部件
	 */
	@SuppressWarnings("unchecked")
	private void initPhotoScrollViewPager() {
		photos = (ArrayList<ALPhoto>) getIntent()
				.getSerializableExtra("photos");
		if (isMyIcon) {
			photos.clear();
			photos = ALLocalEnv.getLocalEnv().getMyProfile().getPhotos();
		}
		adapter = new ImagePagerAdapter(getSupportFragmentManager(),
				photos.size());
		photo_pager.setAdapter(adapter);
		setCenterTextViewMessage((index + 1) + "/" + photos.size());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		super.onClick(v);
	}
	
	/* (non-Javadoc)
	 * @see com.alstudio.ui.base.TitleBarActivity#invokeRightBtnClick()
	 */
	@Override
	protected void invokeRightBtnClick() {
		// TODO Auto-generated method stub
		super.invokeRightBtnClick();
		showPhotoLongClickDialog(index);
	}

	/*************** 弹框 **********************/
	public void showPhotoLongClickDialog(final int position) {

		String[] items = new String[] {
				// 设为主头像
				getString(R.string.TxtSetMainPicture),
				// 相册替换
				getString(R.string.TxtPerPhotoPhotos),
				// 拍照替换
				getString(R.string.TxtPerPhotoCamera),
				// 删除照片
				getString(R.string.TxtDelete), getString(R.string.BtnCancel) };

		final AlertDialogCreator mDialogCreator = AlertDialogCreator
				.createNoButtonWithListItemDialog(this, false, items);

		mDialogCreator.setTitle(getString(R.string.TxtTitleSelectPhoto));

		mDialogCreator.setItemClickListener(new AlItemOnClickListener() {

			@Override
			public void OnClick(int which) {
				switch (which) {
				case 0:
					// 设为主头像
					doChangePhotos(SET_MAJOR_PIC, position);
					break;
				case 1:
					// 从相册替换
					doChangePhotos(SELECT_FOR_REPLACE, position);
					break;
				case 2:
					// 拍照替换
					doChangePhotos(TAKE_FOR_REPLACE, position);
					break;
				case 3:
					// 删除
					doChangePhotos(DELETE_PIC, position);
				}

			}
		});

		mDialogCreator.showDialog();
	}

	/**
	 * 替换V认证图片时的弹出框
	 * 
	 * @param pos
	 * @param select
	 * @param from
	 * @param message
	 */
	private void showReplaceVAuthAlert(final int pos, final int select,
			final String from, final String message) {

		final AlertDialogCreator mDialogCreator = AlertDialogCreator
				.createTwoButtonNormalDialog(this, false);
		mDialogCreator.setMessage(message);
		mDialogCreator.setLeftKeyListener(new AlDialogOnClickListener() {

			@Override
			public void onClick() {
				// TODO Auto-generated method stub
				switch (select) {
				case TAKE_FOR_REPLACE:
					isChange = true;
					takePhotos(mPhotoProcessParam);
					break;
				case SELECT_FOR_REPLACE:
					isChange = true;
					selectPhotos(mPhotoProcessParam);
					break;
				case DELETE_PIC:
					doDelete(pos);
					break;
				case SET_MAJOR_PIC:
					doSetMajorPic(pos);
					break;
				}
			}
		});

		mDialogCreator.showDialog();
	}

	private void doChangePhotos(int type, int pos) {
		switch (type) {
		case TAKE_FOR_REPLACE:
			// 拍照替换
			doTakeReplace(pos);
			break;
		case SELECT_FOR_REPLACE:
			// 选择替换
			doSelectReplace(pos);
			break;
		case DELETE_PIC:
			// 删除图片
			showDelPhotoDialog(pos);
			break;
		case SET_MAJOR_PIC:
			// 设为猪头像
			setPhotoMainPicture(pos);
			break;
		}
	}

	private void doTakeReplace(int pos) {
		if ((ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 2 && pos == ALLocalEnv
				.getLocalEnv().getMyProfile().getvAuthPos())
				|| (ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 1 && pos == ALLocalEnv
						.getLocalEnv().getMyProfile().getvAuthPos())) {
			String msg = "";
			msg = getString(R.string.TxtReplacePicAlert);
			if (ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 1) {
				msg = getString(R.string.TxtDeletAuthedPicAlert);
			}
			showReplaceVAuthAlert(pos, TAKE_FOR_REPLACE, null, msg);
		} else {
			isChange = true;
			takePhotos(mPhotoProcessParam);
		}
	}

	private void doSelectReplace(int pos) {
		if ((ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 2 && pos == ALLocalEnv
				.getLocalEnv().getMyProfile().getvAuthPos())
				|| (ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 1 && pos == ALLocalEnv
						.getLocalEnv().getMyProfile().getvAuthPos())) {
			String msg = "";
			msg = getString(R.string.TxtReplacePicAlert);
			if (ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 1) {
				msg = getString(R.string.TxtDeletAuthedPicAlert);
			}
			showReplaceVAuthAlert(pos, SELECT_FOR_REPLACE, null, msg);
		} else {
			isChange = true;
			selectPhotos(mPhotoProcessParam);
		}
	}

	/**
	 * 删除个人照片提示框
	 * 
	 * @param position
	 */
	private void showDelPhotoDialog(final int position) {
		if ((ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 2 && position == ALLocalEnv
				.getLocalEnv().getMyProfile().getvAuthPos())
				|| (ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 1)
				&& position == ALLocalEnv.getLocalEnv().getMyProfile()
						.getvAuthPos()) {
			showDelectPicMsg(position);
		} else {
			final AlertDialogCreator mDialogCreator = AlertDialogCreator
					.createTwoButtonNormalDialog(this, false);
			mDialogCreator
					.setMessage(getString(R.string.TxtTitleDeletePhotoMsg));
			mDialogCreator.setLeftKeyListener(new AlDialogOnClickListener() {

				@Override
				public void onClick() {
					// TODO Auto-generated method stub
					doDelete(position);
				}
			});

			mDialogCreator.showDialog();
		}

	}

	// 将图片设为主头像
	private void setPhotoMainPicture(final int position) {
		doSetMajorPic(position);
	}

	private void showDelectPicMsg(int pos) {
		if ((ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 2 && pos == ALLocalEnv
				.getLocalEnv().getMyProfile().getvAuthPos())
				|| (ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 1 && pos == ALLocalEnv
						.getLocalEnv().getMyProfile().getvAuthPos())) {
			String msg = "";
			msg = getString(R.string.TxtReplacePicAlert);
			if (ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() == 1) {
				msg = getString(R.string.TxtDeletAuthedPicAlert);
			}
			showReplaceVAuthAlert(pos, DELETE_PIC, null, msg);
		} else {
			doDelete(pos);
		}
	}

	/**
	 * 删除照片
	 * 
	 * @param position
	 */
	private void doDelete(int position) {
		if (position >= photos.size()) {
			return;
		}

		photos.remove(position);
		// ArrayList<ALPhoto> arrayList =
		// ALLocalEnv.getLocalEnv().getMyProfile()
		// .getPhotos();
		// arrayList.remove(position);
		isDel = true;
		saveEditInfo(photos);
		vPos = -1;

		// ALLocalEnv.getLocalEnv().getMyProfile()
		// .setvAuthPos(getVauthPhotoPosition(arrayList));
		if (ALLocalEnv.getLocalEnv().getMyProfile().getVauthed() >= 1
				&& ALLocalEnv.getLocalEnv().getMyProfile().getvAuthPos() == position) {
			cancelVauthed();
		}

	}

	private void cancelVauthed() {
		User u = new User();
		u.setVauthed(0);
		ALLocalEnv.getLocalEnv().getMyProfile().setVauthed(0);
		ALLocalEnv.getLocalEnv().getMyProfile().setvAuthPos(-1);
		ALUiXmppRequestCreator.postALUiXmppModifyUserProfileEvent(u);
	}

	private void saveEditInfo(ArrayList<ALPhoto> arrayList) {
		if (!ALLocalEnv.isSendXmppDataEnable()) {
			return;
		}
		// showLoadingProgress();
		User u = new User();
		u.getPhotos().addAll(arrayList);
		ALUiXmppRequestCreator.postALUiXmppModifyUserProfileEvent(u);
	}

	protected int getVauthPhotoPosition(ArrayList<ALPhoto> list) {
		int pos = -1;
		ALPhoto p = null;
		for (int i = 0; i < list.size(); i++) {
			p = list.get(i);

			if (p.isVauth()) {
				pos = i;
				break;
			}
		}
		return pos;
	}

	private void doSetMajorPic(int position) {
		ArrayList<ALPhoto> list = ALLocalEnv.getLocalEnv().getMyProfile()
				.getPhotos();
		ALPhoto p = list.get(position);
		list.remove(p);
		list.add(0, p);
		photos.clear();
		photos.addAll(list);
		saveEditInfo(list);
	}

	/*************** 弹框 **********************/

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#finish()
	 */
	@Override
	public void finish() {
		super.finish();
	}

	/**
	 * 
	 * 用于查看图片轮播
	 * 
	 * @author alonso lee
	 * 
	 */
	private class ImagePagerAdapter extends FragmentStatePagerAdapter {
		private final int mSize;

		public ImagePagerAdapter(FragmentManager fm, int size) {
			super(fm);
			mSize = size;
		}

		@Override
		public int getCount() {
			return mSize;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			super.destroyItem(container, position, object);
			ALLog.d("销毁图片");

		}

		@Override
		public Fragment getItem(int position) {
			String fileId = photos.get(position).getPicFileid();

			ImageDetailFragment view = ImageDetailFragment.newInstance(fileId);
			view.setmHandler(mHandler);
			return view;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleModifyUserProfileEvent(com.alstudio
	 * .pojo.ALXmppEvent)
	 */
	@Override
	public void handleModifyUserProfileEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleModifyUserProfileEvent(data);
		if (data.getResponseCode() == ALXmppEvent.RESPONSE_OK) {
			ALLog.d("修改资料成功");
			if (isDel) {
				MyToastUtil.getInstance().showToastOnCenter(
						getString(R.string.TxtPhotoHasDel));
				isDel = true;
			} else if (isChange) {
				isChange = false;
			}
			if (adapter != null) {
				adapter = null;
			}
			adapter = new ImagePagerAdapter(getSupportFragmentManager(),
					photos.size());
			photo_pager.setAdapter(adapter);
			photo_pager.setCurrentItem(index);

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.TitleBarActivity#onGetProcessPhotosResult(java.lang
	 * .String, java.lang.String)
	 */
	@Override
	protected void onGetProcessPhotosResult(String path, String name) {
		super.onGetProcessPhotosResult(path, name);
		Uri uri = Uri.fromFile(new File(path));
		ALLog.d("得到图片路径" + uri.toString());
		// 上传图片
		uploadPic(path);
		showLoadingProgress();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.TitleBarActivity#handleUploadPicSuccess(com.alstudio
	 * .utils.android.net.http.UploadPhotoRequest, java.lang.String,
	 * java.lang.String)
	 */
	@Override
	protected void handleUploadPicSuccess(UploadPhotoRequest sender,
			String pictureFileId, String thumbFileId) {
		super.handleUploadPicSuccess(sender, pictureFileId, thumbFileId);
		dismissLoadingProgress();
		ALLog.d("图片上传成功 " + pictureFileId + "小兔 " + thumbFileId);
		ALPhoto tempPhoto = new ALPhoto();
		tempPhoto.setPicFileid(pictureFileId);
		tempPhoto.setThumbnailFileid(thumbFileId);
		if (isChange) {
			ArrayList<ALPhoto> list = ALLocalEnv.getLocalEnv().getMyProfile()
					.getPhotos();
			list.remove(index);
			list.add(index, tempPhoto);
		}
		photos.clear();
		photos.addAll(ALLocalEnv.getLocalEnv().getMyProfile().getPhotos());
		saveEditInfo(photos);
	}
}
